<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select
            filterable
            placeholder="请选择门店"
            v-model="formInline.store_id"
            @change="storeChange"
          >
            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select filterable placeholder="请选择仓" v-model="formInline.house_id">
            <el-option
              v-for="item in houseList"
              :key="item.house_id"
              :label="item.house_name"
              :value="item.house_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="选择类型" v-model="formInline.species" filterable>
            <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.conditions" style="width:140px;">
            <el-option label="搜物品名称" value="3"></el-option>
            <el-option label="搜新物品编号" value="1"></el-option>
            <el-option label="搜神采物品编号" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.accessories_no"
            placeholder="请输入物品编号/名称"
            style="width:160px;"
            @keyup.enter.native="searchClick"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table
        highlight-current-row
        :data="list"
        v-loading.body="listLoading"
        border
        fit
        size="small"
        @sort-change="sortChange"
        ref="sort"
        id="exportContainer"
      >
        <el-table-column align="center" label="图片" width="80">
          <template slot-scope="scope">
            <vue-preview class="preview" :slides="scope.row.imgList"></vue-preview>
          </template>
        </el-table-column>
        <el-table-column align="center" label="物品编号" prop="accessories_id"></el-table-column>
        <el-table-column align="center" label="神采物品编号" prop="no_obsolete" sortable width="120"></el-table-column>
        <el-table-column align="center" label="物品名称" prop="accessories_name"></el-table-column>
        <el-table-column align="center" label="分类" prop="type_name"></el-table-column>
        <el-table-column align="center" label="库存量" prop="num" sortable width="82"></el-table-column>
        <el-table-column align="center" label="实盘数">
          <template slot-scope="scope">
            <el-input
              :ref="'input'+scope.$index"
              @keyup.enter.native="nextFocus(scope.$index)"
              v-model.number="scope.row.calibration_num"
              placeholder="数量"
            ></el-input>
            <span style="display:none">{{scope.row.calibration_num}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="盘点盈亏" sortable>
          <template slot-scope="scope">
            <span
              v-if="scope.row.calibration_num"
              :class="scope.row.calibration_num*1-scope.row.num*1<0?'danger':'success'"
            >{{scope.row.calibration_num*1-scope.row.num*1}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="在库时间(天)" prop="in_house_day" sortable></el-table-column>
        <el-table-column align="center" label="备注">
          <template slot-scope="scope">
            <el-input
              type="text"
              v-model="scope.row.remark"
              :ref="'inputR'+scope.$index"
              @keyup.enter.native="nextRFocus(scope.$index)"
              placeholder="备注"
            ></el-input>
            <span style="display:none">{{scope.row.remark}}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加物品弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="添加盘点物品"
      :visible.sync="addaccessoriesDialog"
      append-to-body
      width="600px"
    >
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input
            type="text"
            placeholder="输入物品编号"
            v-model="search_accessories_no"
            style="width:200px;"
          ></el-input>
          <el-button type="primary" @click="searchaccessoriesClick()">搜 索</el-button>
        </el-form-item>
      </el-form>
      <el-table highlight-current-row :data="searchaccessoriesList" border>
        <el-table-column align="center" property="accessories_name" label="物品名称"></el-table-column>
        <el-table-column align="center" property="accessories_id" label="新物品编号"></el-table-column>
        <el-table-column align="center" property="no_obsolete" label="神采物品编号"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveaccessoriesClick()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <div class="pull-right">
        <el-button
          :disabled="list==null"
          type="primary"
          size="small"
          @click="addaccessoriesClick"
        >添加盘点物品</el-button>
        <el-button
          style="position:relative;overflow:hidden"
          :disabled="!formInline.store_id"
          type="primary"
          size="small"
        >
          <span>库存导入</span>
          <input
            :disabled="!formInline.store_id"
            style="opacity:0;z-index:999;width:100px;height:32px;position:absolute;top:0;left:0"
            type="file"
            ref="importInput"
            @change="importClick"
          />
        </el-button>
        <el-button
          :disabled="list==null||list.length==0"
          type="primary"
          size="small"
          @click="exportExcel"
        >库存盘点表导出</el-button>
        <el-button :disabled="no_check" type="primary" size="small" @click="saveClick(0)">库存核准</el-button>
        <el-button
          :loading="is_save"
          :disabled="no_check||no_save"
          type="primary"
          size="small"
          @click="saveClick(1)"
        >{{is_save?'提交中':'提交保存'}}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getList,
  storeList,
  save,
  houseList,
  searchaccessories,
  get_goods_type,
  // importForm,
} from "@/api/storage_control/pj_inventory";
import Cookies from "js-cookie";
import axios from "axios";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  data() {
    return {
      is_save: false,
      type_list: null,
      fileList: [],
      no_check: true,
      no_save: true,
      machineInfo: "",
      addaccessoriesDialog: false,
      list: null,
      listLoading: false,
      searchaccessoriesList: [],
      storeList: [],
      houseList: [],
      search_accessories_no: "",
      formInline: {
        species: "",
        store_id: "",
        house_id: "",
        orderby: "",
        accessories_no: "",
        conditions: "3",
      },
      saveForm: {
        store_id: "",
        house_id: "",
        check_list: [],
      },
      infoText: "",
      url: "",
      accessoriesInfo: [],
      infoDialog: false,
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.type_list) {
        vm.getGoods();
        vm.getStoreList();
      }
    });
  },
  // created() {
  //     this.getStoreList();
  //     this.getGoods();
  // },
  methods: {
    getGoods() {
      get_goods_type({ category_id: this.$route.meta.id }).then((response) => {
        response.forEach((item) => {
          if (item.name == "配件类物品") {
            item.id = 1;
          } else if (item.name == "财务类物品") {
            item.id = 2;
          } else if (item.name == "其他类物品") {
            item.id = 3;
          }
        });
        this.type_list = response;
        this.formInline.species = response.length > 0 ? response[0].id : "";
      });
    },
    nextFocus(index) {
      for (let i = 1; i < this.list.length; i++) {
        let focusIndex = index + i;
        let inputRef = "input" + focusIndex;
        if (this.$refs[inputRef]) {
          this.$refs[inputRef].$el.children[0].focus();
          return;
        }
      }
    },
    nextRFocus(index) {
      for (let i = 1; i < this.list.length; i++) {
        let focusIndex = index + i;
        let inputRef = "inputR" + focusIndex;
        if (this.$refs[inputRef]) {
          this.$refs[inputRef].$el.children[0].focus();
          return;
        }
      }
    },
    // 前端导出
    exportExcel() {
      /* generate workbook object from table */
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#exportContainer")
      );
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          `${this.$route.meta.title}.xlsx`
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    sortChange(column, prop, order) {
      if (column.column && column.column.label == "盘点盈亏") {
        let ok = true;
        this.list.forEach((val) => {
          if (val.calibration_num == "" || val.calibration_num == null) {
            this.$refs.sort.columns[9].order = "";
            this.$message({
              type: "warning",
              message: "盘点盈亏排序仅在所有实盘数填完才能使用哦",
            });
            return (ok = false);
          }
        });
        if (ok) {
          this.list.sort((a, b) => {
            if (column.order == "ascending") {
              if (
                a.calibration_num * 1 - a.num * 1 <
                b.calibration_num * 1 - b.num * 1
              ) {
                return -1;
              }
              if (
                a.calibration_num * 1 - a.num * 1 >
                b.calibration_num * 1 - b.num * 1
              ) {
                return 1;
              }
              return 0;
            } else if (column.order == "descending") {
              if (
                a.calibration_num * 1 - a.num * 1 >
                b.calibration_num * 1 - b.num * 1
              ) {
                return -1;
              }
              if (
                a.calibration_num * 1 - a.num * 1 <
                b.calibration_num * 1 - b.num * 1
              ) {
                return 1;
              }
              return 0;
            }
          });
        }
      }
    },
    //导入功能  在请求头统一设置了data转换成后端需要的字符串，文件上传请求暂时写在VUE文件里
    importClick(e) {
      const that = this;
      console.log(
        e.target.files[0].name.substring(e.target.files[0].name.length - 3)
      );
      if (
        e.target.files[0].name.substring(e.target.files[0].name.length - 3) !=
        "csv"
      ) {
        that.$message({ type: "error", message: "请选择csv文件上传" });
        return;
      }
      let formData = new FormData();
      formData.append("store_id", this.formInline.store_id);
      formData.append("house_id", this.formInline.house_id);
      formData.append("check_csv", e.target.files[0]);
      let url = `https://${location.host}/smsi/index.php/Stock_check/accessories_back_csv`;
      let config = {
        headers: { didixueshengka: `${Cookies.get("SMS_AdminToken")}` },
      };
      axios.post(url, formData, config).then(function (response) {
        that.$message({
          type: response.data.code == 1 ? "success" : "error",
          message: response.data.message,
        });
        that.$refs.importInput.value = "";
        if (response.data.code == 1) {
          that.fetchData();
        }
      });
    },
    info(index) {
      this.accessoriesInfo = [];
      this.infoDialog = true;
      this.accessoriesInfo[0] = this.list[index];
    },
    saveClick(type) {
      // console.log(this.list)
      let ok = true;
      for (let i = 0; i < this.list.length; i++) {
        if (
          this.list[i].calibration_num === "" ||
          this.list[i].calibration_num === null
        ) {
          ok = false;
          this.$message({
            type: "error",
            message: "请将实盘数填写完整,实盘数只能为整数",
          });
          break;
        }
        if (
          this.list[i].calibration_num < 0 ||
          !/^\d+$/.test(this.list[i].calibration_num)
        ) {
          ok = false;
          this.$message({ type: "error", message: "实盘数只能为整数" });
          break;
        }
      }
      if (ok) {
        this.infoText =
          type == 1
            ? "请将盘点仓库所有物品库存核准,所有数据一经提交，当天不可再做修改"
            : "该操作为核准库存";
        this.url =
          type == 1
            ? "/Stock_check/accessories_do_check"
            : "/Stock_check/accessories_calibration_save";
        this.$confirm(this.infoText, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.saveForm.store_id = this.formInline.store_id;
          this.saveForm.house_id = this.formInline.house_id;
          this.saveForm.check_list = [];

          for (let i = 0; i < this.list.length; i++) {
            this.saveForm.check_list.push({
              remark: this.list[i].remark,
              accessories_id: this.list[i].accessories_id,
              check_num: this.list[i].calibration_num,
            });
          }
          if (type == 1) {
            this.is_save = true;
          }
          save(this.saveForm, this.url).then((response) => {
            this.$message({
              type: response.code == 1 ? "success" : "error",
              message: response.message,
            });
            if (response.code == 1) {
              this.is_save = false;
              this.fetchData();
            }
          });
        });
      }
    },
    storeChange() {
      this.getHouseList();
    },
    // 确定物品
    saveaccessoriesClick() {
      this.list.push(this.searchaccessoriesList[0]);
      this.$message({ type: "success", message: "已添加到列表，请核准" });
      this.addaccessoriesDialog = false;
    },
    addaccessoriesClick() {
      this.addaccessoriesDialog = true;
      this.searchaccessoriesList = [];
    },
    searchaccessoriesClick() {
      let ok = true;
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].accessories_id == this.search_accessories_no) {
          ok = false;
          this.$message({
            type: "error",
            message: "该物品已存在于库存盘点界面请勿重复添加",
          });
          break;
        }
      }
      if (ok) {
        let data = {
          accessories_no: this.search_accessories_no,
          store_id: this.formInline.store_id,
          house_id: this.formInline.house_id,
          species: this.formInline.species,
        };
        this.listLoading = true;
        searchaccessories(data).then((response) => {
          if (response.length == 0) {
            this.$message({
              type: "error",
              message: "该物品不存在于主仓（中转仓）中",
            });
          }
          response.forEach((val, i) => {
            val.imgList = [
              {
                src: val.img,
                msrc: val.thumb,
                w: 1200,
                h: 900,
              },
            ];
          });
          this.searchaccessoriesList = response;
          this.listLoading = false;
        });
      }
    },
    searchClick() {
      if (this.formInline.store_id) {
        this.fetchData();
      } else {
        this.$message({ type: "error", message: "请选择门店" });
      }
    },
    getStoreList() {
      storeList({ category_id: 86 }).then((response) => {
        this.storeList = response;
        let data = response.filter(
          (res) => res.id == this.$store.getters.optionId
        );
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
        } else {
          if (this.storeList.length > 0) {
            this.formInline.store_id = this.storeList[0].id;
          }
        }
        this.getHouseList();
      });
    },
    getHouseList() {
      houseList({ store_id: this.formInline.store_id, cang: 2 }).then(
        (response) => {
          this.houseList = response;
          if (this.houseList.length > 0) {
            this.formInline.house_id = response[0].house_id;
          } else {
            this.formInline.house_id = "";
          }
        }
      );
    },
    // 列表获取
    fetchData() {
      this.no_save = true;
      this.no_check = true;
      this.listLoading = true;
      getList(this.formInline).then((response) => {
        response.forEach((val, i) => {
          val.calibration_num =
            val.calibration_num == null ? "" : val.calibration_num;
          val.imgList = [
            {
              src: val.img,
              msrc: val.thumb,
              w: 1200,
              h: 900,
            },
          ];
        });
        this.list = response;
        if (response.length > 0) {
          this.no_save = response[0].calibration_num ? false : true;
          this.no_check = response[0].ok == 0 ? true : false;
        }
        this.listLoading = false;
      });
    },
  },
};
</script>